package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"social-app/models"
	"social-app/pkg/err_msg"
	"social-app/pkg/jwt_token"
	"social-app/pkg/response"
	"strconv"
	"strings"
	"time"
)

type DynamicController struct{}

type successResponse struct {
	DynamicId    int       `json:"dynamic_id"`
	UserId       int       `json:"user_id"`
	CategoryName string    `json:"category_name"`
	Content      string    `json:"content"`
	Images       []string  `json:"images"`
	Tags         []string  `json:"tags"`
	Video        string    `json:"video"`
	Music        string    `json:"music"`
	ReplyCount   int       `json:"reply_count"`
	PraiseCount  int       `json:"praise_count"`
	PraiseStatus int       `json:"praise_status"`
	CreateTime   time.Time `json:"create_time"`
}

func (d DynamicController) Create(c *gin.Context) {
	UserId := jwt_token.GetUserId(c)
	type Params struct {
		CategoryId int      `json:"category_id" binding:"required"`
		Content    string   `json:"content" binding:"required,max=100"`
		Images     []string `json:"images"`
		Tags       []string `json:"tags"`
		Video      string   `json:"video"`
		Music      string   `json:"music"`
	}
	var params Params
	if err := c.ShouldBind(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, map[string]string{
			"CategoryId.required": "动态分类ID必传",
			"Content.required":    "动态内容不能为空",
			"Content.max":         "动态内容不能超过100个字符",
		}))
	}

	ip := c.ClientIP()
	dynamic, err := models.CreateDynamic(UserId, params.CategoryId, params.Content, params.Images, params.Video, params.Music, params.Tags, ip)
	if err != nil {
		panic(err.Error())
	}
	type successResponse struct {
		DynamicId int `json:"dynamic_id"`
	}
	response.Success(c, "发布成功", &successResponse{
		DynamicId: dynamic.Id,
	})
}

func (d DynamicController) List(c *gin.Context) {
	type reqParams struct {
		CategoryId int    `form:"category_id"`
		Page       int    `form:"page" binding:"required,min=1"`
		Limit      int    `form:"limit" binding:"required,min=1,max=100"`
		OrderBy    string `form:"order_by" binding:"omitempty,oneof=create_time"`
		Desc       string `form:"desc" binding:"omitempty,oneof=desc asc"`
	}

	var params reqParams
	if err := c.ShouldBindQuery(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, nil))
	}
	if params.OrderBy == "" {
		params.OrderBy = "create_time"
	}
	if params.Desc == "" {
		params.Desc = "desc"
	}

	orderBy := fmt.Sprintf("%s %s", params.OrderBy, params.Desc)
	list, err := models.GetDynamicList(params.CategoryId, params.Page, params.Limit, orderBy)
	if err != nil {
		panic("获取列表错误")
	}
	var successListResponse []successResponse
	for _, value := range list {
		successListResponse = append(successListResponse, successResponse{
			DynamicId:    value.Id,
			UserId:       value.UserId,
			Content:      value.Content,
			Images:       strings.Split(value.Images, ","),
			Tags:         strings.Split(value.Tags, ","),
			Video:        value.Video,
			Music:        value.Music,
			CreateTime:   value.CreateTime,
			CategoryName: value.CategoryName,
			PraiseCount:  value.PraiseCount,
			ReplyCount:   value.ReplyCount,
			PraiseStatus: value.PraiseStatus,
		})
	}
	response.Success(c, "获取成功", &successListResponse)
}

func (d DynamicController) Get(c *gin.Context) {
	dynamicIdStr := c.Param("id")
	dynamicId, _ := strconv.Atoi(dynamicIdStr)
	dynamic, err := models.GetDynamicById(dynamicId)
	if err != nil {
		panic(err.Error())
	}
	response.Success(c, "获取成功", successResponse{
		DynamicId:    dynamic.Id,
		UserId:       dynamic.UserId,
		Content:      dynamic.Content,
		Images:       strings.Split(dynamic.Images, ","),
		Tags:         strings.Split(dynamic.Tags, ","),
		Video:        dynamic.Video,
		Music:        dynamic.Music,
		CreateTime:   dynamic.CreateTime,
		CategoryName: dynamic.CategoryName,
		PraiseCount:  dynamic.PraiseCount,
		ReplyCount:   dynamic.ReplyCount,
		PraiseStatus: dynamic.PraiseStatus,
	})
}

func (d DynamicController) Praise(c *gin.Context) {
	dynamicIdStr := c.Param("id")
	dynamicId, _ := strconv.Atoi(dynamicIdStr)
	userId := jwt_token.GetUserId(c)
	praise := (&models.DynamicPraise{}).Create(userId, dynamicId)
	if praise.Id == 0 {
		_ = models.DynamicPraiseSub(dynamicId)
		response.Success(c, "取消点赞成功", nil)
	} else {
		_ = models.DynamicPraiseInc(dynamicId)
		response.Success(c, "点赞成功", nil)
	}
}
